import ctypes
import os
import time

dll: ctypes.CDLL  = None

def tar_rust(file_path, dll_path = None):
    global dll
    if dll is None:
        dll = ctypes.CDLL(dll_path)

    dll.list_files_in_tgz.argtypes = [ctypes.c_char_p]
    dll.list_files_in_tgz.restype = ctypes.POINTER(ctypes.POINTER(ctypes.c_char))
    dll.free_string_array.argtypes = [ctypes.POINTER(ctypes.POINTER(ctypes.c_char))]

    result_ptr = dll.list_files_in_tgz(file_path.encode('utf-8'))
    if not result_ptr:
        print("Function execution failed: No data returned.")
        return

    filenames = []
    index = 0
    while True:
        c_str_ptr = result_ptr[index]
        if not c_str_ptr:
            break
        decoded = ctypes.cast(c_str_ptr, ctypes.c_char_p).value.decode('utf-8')
        if decoded.startswith("ERROR:"):
            print(f"Error: {decoded}")
            dll.free_string_array(result_ptr)
            return
        filenames.append(decoded)
        index += 1

    dll.free_string_array(result_ptr)
    return filenames


if __name__ == "__main__":

    file_path = "/home/apple/tmp/bigfile.tar.gz"
    # file_path = "/home/apple/tmp/abctrest.tar.gz"  
    dll = ctypes.CDLL("../lib/rust_tar_library.dll")
    start_time = time.perf_counter()
    filenames = tar_rust(file_path)

    end_time = time.perf_counter()
    method1_time = end_time - start_time

    for filename in filenames:
        print(filename)

    print(f"Method  took {method1_time:.6f} seconds")
